<template>
  <div class="user-management">
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <!-- 搜索框 -->
      <el-input v-model="searchKeyword" placeholder="输入用户名、昵称、联系电话或创建人搜索讲师" class="search-input" @keyup.enter="searchUsers">
        <template #append>
          <el-button type="primary" @click="searchUsers">
            <Search />
            搜索
          </el-button>
        </template>
      </el-input>

      <!-- 添加按钮和批量删除按钮 -->
      <div class="right-buttons">
        <!-- 批量删除按钮：危险类型，仅在选中项不为空时启用 -->
        <!-- 使用删除图标增强视觉识别性，红色背景明确表示危险操作 -->
        <el-button 
          type="danger" 
          icon="Delete"          
          @click="handleBatchDelete"
          :disabled="selectedUsers.length === 0"
          style="margin-right: 8px;"
        >
          批量删除
        </el-button>
        <el-button type="primary" icon="Plus" @click="showAddDialog = true">
          添加讲师
        </el-button>
      </div>
    </div>

    <!-- 表格展示讲师数据 -->
    <!-- 添加selection-change事件监听选中项变化 -->
    <el-table 
      :data="currentPageData" 
      border 
      stripe 
      style="width: 100%" 
      :row-key="row => row.userId"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userId" label="用户ID" width="80" align="center" />
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column prop="nickname" label="讲师姓名" width="120" />
      <el-table-column prop="contact" label="联系方式" width="150" />
      <el-table-column prop="avatarUrl" label="头像">
        <template #default="scope">
          <img :src="scope.row.avatarUrl" alt="头像" width="50" />
        </template>
      </el-table-column>
      <!-- 角色列：使用标签组件美化显示 -->
      <el-table-column label="角色" width="100" align="center">
        <template #default="scope">
          <el-tag :type="roleType(scope.row.roleId)" size="small">
            {{ roleName(scope.row.roleId) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 美化创建人显示 -->
      <el-table-column prop="creator" label="创建人" width="120" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.creator === 'system'" type="info" size="small">系统默认</el-tag>
          <span v-else>{{ scope.row.creator || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后更新时间" width="180" align="center">
        <template #default="scope">
          {{ scope.row.updateTime ? scope.row.updateTime: '-' }}
        </template>
      </el-table-column>
      <!-- 美化最后更新人显示 -->
      <el-table-column prop="updater" label="最后更新人" width="120" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.updater" type="primary" size="small">{{ scope.row.updater }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" icon="Edit" size="small" @click="editUser(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" icon="Delete" size="small" @click="deleteUser(scope.row.userId)" style="margin-left: 8px;">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination 
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px;"
    />

    <!-- 添加讲师对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加讲师"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form ref="addFormRef" :model="newUser" label-width="100px" :rules="formRules">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="newUser.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="讲师姓名" prop="nickname">
          <el-input v-model="newUser.nickname" placeholder="请输入讲师姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="newUser.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="newUser.avatarUrl" placeholder="请输入头像URL"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <!-- 使用:value单向绑定替代v-model，因为角色是固定的且输入框禁用 -->
          <el-input :value="roleName(newUser.roleId)" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addUser">提交</el-button>
      </template>
    </el-dialog>

    <!-- 编辑讲师对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑讲师"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form ref="editFormRef" :model="editingUser" label-width="100px" :rules="formRules">
        <el-form-item label="用户ID">
          <el-input v-model.number="editingUser.userId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editingUser.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="讲师姓名" prop="nickname">
          <el-input v-model="editingUser.nickname" placeholder="请输入讲师姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editingUser.password" type="password" placeholder="不填表示不修改"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="editingUser.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="editingUser.avatarUrl" placeholder="请输入头像URL"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <!-- 使用:value单向绑定替代v-model -->
          <el-input :value="roleName(editingUser.roleId)" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateUser">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 导入Element Plus组件和图标，新增ElTag组件
import { ElButton, ElInput, ElTable, ElTableColumn, ElPagination, ElDialog, ElForm, ElFormItem, ElTag } from 'element-plus';
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';
import { useInstructorUser } from '@/ViewsScript/Backend/InstructorUser.ts';
import { ref } from 'vue';
import type { User } from '@/ViewsScript/Backend/InstructorUser.ts'; // 导入User类型定义

// 表单验证规则
const formRules = ref({
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '讲师姓名不能为空', trigger: 'blur' }
  ]
});

// 表单引用
const addFormRef = ref<InstanceType<typeof ElForm>>();
const editFormRef = ref<InstanceType<typeof ElForm>>();

// 存储选中的用户
// 使用泛型ref确保类型安全，初始化为空数组
const selectedUsers = ref<User[]>([]);

// 处理表格选中项变化
// 实时更新选中用户列表，用于控制批量删除按钮状态
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection;
};

// 解构组合式函数返回的状态和方法
const {
  userList,
  showAddDialog,
  showEditDialog,
  newUser,
  editingUser,
  searchKeyword,
  currentPage,
  pageSize,
  total,
  currentPageData,
  
  fetchUsers,
  addUser,
  resetNewUser,
  deleteUser,
  editUser,
  updateUser,
  searchUsers,
  handleSizeChange,
  handleCurrentChange,
  roleName,
  roleType,
  handleBatchDelete // 批量删除方法
} = useInstructorUser(selectedUsers);
</script>

<style scoped>
/* 用户管理容器样式：设置为flex布局，垂直排列子元素 */
/* 使用calc(100vh - 120px)计算可用高度，减去顶部导航栏等固定元素的高度 */
/* box-sizing: border-box确保padding不会增加总高度，避免出现全局滚动条 */
.user-management {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  padding: 20px;
  box-sizing: border-box;
}

/* 操作按钮区域样式 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 搜索框样式 */
.search-input {
  width: 500px;
}

/* 右侧按钮组样式 */
.right-buttons {
  display: flex;
  gap: 12px;
}

/* 表格容器样式：flex:1使容器占据剩余空间 */
/* overflow-y:auto在内容溢出时显示垂直滚动条，实现表格内容滚动 */
.table-container {
  flex: 1;
  overflow-y: auto;
}
</style>